package com.leetcode.Offer;

import java.util.LinkedHashMap;

public class JZ50 {
    //使用LinkedHashMap保证有序
    public char firstUniqChar(String s) {

        if (s.length() == 0) {
            return ' ';
        }

        LinkedHashMap<Character, Boolean> map = new LinkedHashMap<>();
        char[] chars = s.toCharArray();
        for (char aChar : chars) {
            if (map.containsKey(aChar)) {
                map.put(aChar, false);
            } else {
                map.put(aChar, true);
            }
        }
        char rs = 0;
        for (Character character : map.keySet()) {
            if (map.get(character)) {
                rs = character;
                break;
            }
        }
        return rs == 0 ? ' ' : rs;
    }

    //使用count计数法,效率更高
    public char firstUniqChar2(String s) {

        if (s == null || s.length() == 0) {
            return ' ';
        }

        char[] chars = s.toCharArray();
        int[] count = new int['z' - 'a' + 1];
        for (char aChar : chars) {
            count[aChar - 'a']++;
        }
        for (int i = 0; i < s.length(); i++) {
            if (count[chars[i] - 'a'] == 1) {
                return chars[i];
            }
        }

        return ' ';
    }
}
